from django.db import models
from utils import geocode_address
import urllib
from django.utils.translation import ugettext_lazy as _
from django.utils.safestring import mark_safe
from garetjax.maps.fields import CoordinatesField

class CH_City(models.Model):
    postal_code = models.PositiveSmallIntegerField()
    name = models.CharField(max_length=100)
    latitude = models.FloatField(blank=True, null=True, editable=False)
    longitude = models.FloatField(blank=True, null=True, editable=False)
    
    def __unicode__(self):
        return u'%s %s' % (self.postal_code, self.name)
    
    def save(self, **options):
        query = 'CH-%s %s' % (self.postal_code, self.name)
        self.latitude, self.longitude = geocode_address(query)
        super(self.__class__, self).save(**options)
    
    def gmap_link(self):
        # Uncomment the next line to use coordinates in the query on google maps
        #return 'http://maps.google.com/?q=%f,%f' % (self.latitude, self.longitude)
        
        return 'http://maps.google.com/?q=%s' % self.name
    gmap_link.short_description = _('Google Maps link')
    
    def get_absolute_url(self):
        return self.gmap_link()
    
    class Meta:
        verbose_name = _('swiss city')
        verbose_name_plural = _('swiss cities')
        unique_together = (('postal_code', 'name'),)

class Location(models.Model):
    name = models.CharField(max_length=100)
    place = models.TextField(max_length=100)
    latitude = models.FloatField(blank=True, null=True)
    longitude = models.FloatField(blank=True, null=True)
    description = models.TextField(blank=True)
    link = models.URLField(blank=True)
    
    def __unicode__(self):
        return self.name